use regex::Regex;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    // TODO: 这里写逻辑
    // use regex to extract the number and base
    let re = Regex::new(r"(\d+)\((\d+)\)").unwrap();
    if let Some(captures) = re.captures(num_str) {
        let num = captures.get(1).unwrap().as_str();
        let from_base = captures.get(2).unwrap().as_str().parse::<u32>().unwrap();

        // Convert the number to base 10 from the given from_base
        let num = i64::from_str_radix(num, from_base).unwrap();
        to_base_string(num, to_base)
    } else {
        return "Invalid input".to_string();
    }
}

fn to_base_string(mut num:i64, base: u32) -> String {
    if num == 0 {
        return "0".to_string();
    }

    let mut result = String::new();
    let chars = "0123456789abcdef".chars().collect::<Vec<char>>();
    while num > 0 {
        // get the remainder of the number divided by the base
        let rem = (num % base as i64) as usize;
        // push the character representation of the remainder to the result
        result.push(chars[rem]);
        // divide the number by the base
        num /= base as i64;
    }   
    result.chars().rev().collect::<String>()
}